package com.sykj.cloud.system.controller;

import com.sykj.cloud.common.core.constant.UserConstants;
import com.sykj.cloud.common.core.domain.R;
import com.sykj.cloud.common.core.utils.StringUtils;
import com.sykj.cloud.common.core.utils.poi.ExcelUtil;
import com.sykj.cloud.common.core.web.controller.BaseController;
import com.sykj.cloud.common.core.web.domain.AjaxResult;
import com.sykj.cloud.common.core.web.page.TableDataInfo;
import com.sykj.cloud.common.log.annotation.Log;
import com.sykj.cloud.common.log.enums.LogUserType;
import com.sykj.cloud.common.security.annotation.PreAuthorize;
import com.sykj.cloud.common.security.utils.SecurityUtils;
import com.sykj.cloud.system.api.domain.SysRole;
import com.sykj.cloud.system.api.domain.SysUser;
import com.sykj.cloud.system.api.model.LoginUser;
import com.sykj.cloud.system.service.ISysPermissionService;
import com.sykj.cloud.system.service.ISysRoleService;
import com.sykj.cloud.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 系统用户Controller
 *
 * @author mr.will
 * @date 2021-03-23
 */
@RestController
@RequestMapping("/user")
public class SysUserController extends BaseController
{
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    ISysRoleService roleService;

    @Autowired
    ISysPermissionService permissionsService;

    /**
     * 新增系统用户
     */
    @PreAuthorize(hasPermi = "system:user:add")
    @Log(title = "系统用户", logUserType = LogUserType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysUser sysUser)
    {
        if (UserConstants.NOT_UNIQUE.equals(sysUserService.checkLoginNameUnique(sysUser.getLoginName())))
        {
            return AjaxResult.error("新增用户'" + sysUser.getLoginName() + "'失败，登录名已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(sysUserService.checkPhoneUnique(sysUser)))
        {
            return AjaxResult.error("新增用户'" + sysUser.getLoginName() + "'失败，手机号码已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(sysUserService.checkEmailUnique(sysUser)))
        {
            return AjaxResult.error("新增用户'" + sysUser.getLoginName() + "'失败，邮箱账号已存在");
        }
        return toAjax(sysUserService.insertSysUser(sysUser));
    }

    /**
     * 修改系统用户
     */
    @PreAuthorize(hasPermi = "system:user:edit")
    @Log(title = "系统用户", logUserType = LogUserType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysUser sysUser)
    {
//        userService.checkUserAllowed(user);
        if (UserConstants.NOT_UNIQUE.equals(sysUserService.checkPhoneUnique(sysUser)))
        {
            return AjaxResult.error("修改用户'" + sysUser.getLoginName() + "'失败，手机号码已存在");
        }
        else if (UserConstants.NOT_UNIQUE.equals(sysUserService.checkEmailUnique(sysUser)))
        {
            return AjaxResult.error("修改用户'" + sysUser.getLoginName() + "'失败，邮箱账号已存在");
        }
        return toAjax(sysUserService.updateSysUser(sysUser));
    }

    /**
     * 状态修改
     */
    @PreAuthorize(hasPermi = "system:user:edit")
    @Log(title = "系统用户", logUserType = LogUserType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user)
    {
//        sysUserService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(sysUserService.updateSysUserVaildStatus(user));
    }


    /**
     * 重置密码
     */
    @PreAuthorize(hasPermi = "system:user:edit")
    @Log(title = "用户管理", logUserType = LogUserType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user)
    {
//        userService.checkUserAllowed(user);
        user.setLoginPassword(SecurityUtils.encryptPassword(user.getLoginPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(sysUserService.resetPwd(user));
    }

    /**
     * 删除系统用户
     */
    @PreAuthorize(hasPermi = "system:user:remove")
    @Log(title = "系统用户", logUserType = LogUserType.DELETE)
	@DeleteMapping("/{guids}")
    public AjaxResult remove(@PathVariable String[] guids)
    {
        return toAjax(sysUserService.deleteSysUserByIds(guids));
    }

//    /**
//     * 获取系统用户详细信息
//     */
//    @PreAuthorize(hasPermi = "system:user:query")
//    @GetMapping(value = "/{guid}")
//    public AjaxResult getInfos(@PathVariable("guid") String guid)
//    {
//        return AjaxResult.success(sysUserService.getSysUserById(guid));
//    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize(hasPermi = "system:user:query")
    @GetMapping(value = {"/","/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) String userId)
    {
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.listRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
//        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId))
        {
            ajax.put(AjaxResult.DATA_TAG, sysUserService.getSysUserById(userId));
//            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", roleService.listRolesByUserId(userId));
        }
        return ajax;
    }

    /**
     * 导出系统用户列表
     */
    @PreAuthorize(hasPermi = "system:user:export")
    @Log(title = "系统用户", logUserType = LogUserType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser sysUser) throws IOException
    {
        List<SysUser> list = sysUserService.listSysUsers(sysUser);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "user");
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/info/{loginName}")
    public R<LoginUser> info(@PathVariable("loginName") String loginName)
    {
        SysUser sysUser = sysUserService.getUserByLoginName(loginName);
        if (StringUtils.isNull(sysUser))
        {
            return R.fail("用户名或密码错误");
        }
        // 角色集合
        Set<String> roles = permissionsService.getRolePermission(sysUser.getGuid());
        // 权限集合
        Set<String> permissions = permissionsService.getMenuPermission(sysUser.getGuid());
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setSysUser(sysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setPermissions(permissions);
        return R.ok(sysUserVo);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        String userId = SecurityUtils.getUserIds();
        // 角色集合
        Set<String> roles = permissionsService.getRolePermission(userId);
        // 权限集合
        Set<String> permissions = permissionsService.getMenuPermission(userId);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", sysUserService.getSysUserById(userId));
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 查询系统用户列表
     */
    @PreAuthorize(hasPermi = "system:user:list")
    @GetMapping("/list")
    public TableDataInfo list(SysUser sysUser)
    {
        startPage();
        List<SysUser> list = sysUserService.listSysUsers(sysUser);
        return getDataTable(list);
    }

    /**
     * 查询站点信息，下拉框值
     */
    @PreAuthorize(hasPermi = "system:user:list")
    @GetMapping("/list/options")
    public AjaxResult optionList(SysUser sysUser)
    {
        return AjaxResult.success(sysUserService.listSysUsers(sysUser));
    }
}
